<template>
  <div class="container">
    <div class="header">
      <h1>委托订单管理</h1>
      <p>查看和管理您的所有委托订单</p>
    </div>

    <div class="order-table">
      <div class="table-header">
        <div class="table-title">订单列表</div>
        <div class="order-count">共 {{ orders.length }} 个订单</div>
      </div>

      <div v-if="loading" class="loading">
        <p>正在加载订单数据...</p>
      </div>

      <div v-else-if="orders.length === 0" class="empty-state">
        <h3>暂无委托订单</h3>
        <p>您还没有任何委托订单</p>
      </div>

      <!-- 桌面端表格 -->
      <div class="desktop-table">
        <table>
          <thead>
          <tr>
            <th>订单ID</th>
            <th>股票代码</th>
            <th>单股价格</th>
            <th>购买数量</th>
            <th>订单总额</th>
            <th>交易类型</th>
            <th>订单状态</th>
            <th>操作</th>
            <th>订单时间</th>
          </tr>
          </thead>
          <tbody>
          <tr v-for="order in orders" :key="order.orderId">
            <td>{{ order.orderId }}</td>
            <td class="stock-symbol">{{ order.stockSymbol }}</td>
            <td class="amount">¥{{ formatNumber(order.orderAmount) }}</td>
            <td>{{ formatNumber(order.stockQuantity) }}</td>
            <td class="amount" :class="order.buySell.toLowerCase() === 'buy' ? 'negative' : 'positive'">
              ¥{{ formatNumber(order.orderAllAmount) }}
            </td>
            <td>
                <span class="buy-sell" :class="order.buySell.toLowerCase() === 'buy' ? 'buy' : 'sell'">
                  {{ order.buySell.toLowerCase() === 'buy' ? '买入' : '卖出' }}
                </span>
            </td>
            <td>
                <span class="status" :class="`status-${getStatusClass(order.status)}`">
                  {{ getStatusText(order.status) }}
                </span>
            </td>
            <td>
              <button
                  v-if="order.status.toLowerCase() === 'ing'"
                  class="cancel-btn"
                  @click="showCancelModal(order)"
              >
                撤销
              </button>
              <span v-else style="color: #ccc;">-</span>
            </td>
            <td>{{order.createdAt}}</td>
          </tr>
          </tbody>
        </table>
      </div>

      <!-- 移动端卡片布局 -->
      <div class="mobile-cards">
        <div v-for="order in orders" :key="order.orderId" class="order-card">
          <div class="card-header">
            <div class="card-title">
              <span class="order-id">#{{ order.orderId }}</span>
              <span class="stock-symbol">{{ order.stockSymbol }}</span>
              <span class="order-time">{{order.createdAt}}</span>
            </div>
            <div class="card-status">
              <span class="status" :class="`status-${getStatusClass(order.status)}`">
                {{ getStatusText(order.status) }}
              </span>
            </div>
          </div>

          <div class="card-content">
            <div class="card-row">
              <div class="card-item">
                <span class="label">交易类型</span>
                <span class="buy-sell" :class="order.buySell.toLowerCase() === 'buy' ? 'buy' : 'sell'">
                  {{ order.buySell.toLowerCase() === 'buy' ? '买入' : '卖出' }}
                </span>
              </div>
              <div class="card-item">
                <span class="label">单股价格</span>
                <span class="value">¥{{ formatNumber(order.orderAmount) }}</span>
              </div>
            </div>

            <div class="card-row">
              <div class="card-item">
                <span class="label">购买数量</span>
                <span class="value">{{ formatNumber(order.stockQuantity) }}股</span>
              </div>
              <div class="card-item">
                <span class="label">订单总额</span>
                <span class="value amount" :class="order.buySell.toLowerCase() === 'buy' ? 'negative' : 'positive'">
                  ¥{{ formatNumber(order.orderAllAmount) }}
                </span>
              </div>
            </div>
          </div>

          <div v-if="order.status.toLowerCase() === 'ing'" class="card-actions">
            <button class="cancel-btn-mobile" @click="showCancelModal(order)">
              撤销订单
            </button>
          </div>

        </div>
      </div>
    </div>

    <!-- 撤销确认模态框 -->
    <div v-if="cancelModal.show" class="modal-overlay" @click="cancelModal.show = false">
      <div class="modal" @click.stop>
        <h3>确认撤销订单</h3>
        <p>您确定要撤销订单 <strong>{{ cancelModal.order?.orderId }}</strong> 吗？</p>
        <p style="font-size: 14px; color: #999;">
          {{ cancelModal.order?.stockSymbol }} |
          {{ cancelModal.order?.buySell === 'BUY' ? '买入' : '卖出' }} |
          {{ formatNumber(cancelModal.order?.stockQuantity) }}股
        </p>
        <div class="modal-actions">
          <button class="btn btn-secondary" @click="cancelModal.show = false">
            取消
          </button>
          <button class="btn btn-danger" @click="cancelOrder">
            确认撤销
          </button>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import { ref, onMounted } from 'vue'
import {getUserOrder} from "@/api/user/userget";
import {userCancelOrder} from "@/api/user/userother";
import toast from "@/utils/toast";
export default {
  name: 'UserOrder',
  setup() {
    const loading = ref(true)
    const orders = ref([])
    const cancelModal = ref({
      show: false,
      order: null
    })

    // 加载订单数据
    const loadOrders = async () => {
      try {
        const {data}=await getUserOrder()
        orders.value=data

        setTimeout(() => {
          loading.value = false
        }, 800)
      } catch (error) {
        console.error('加载订单失败:', error)
        loading.value = false
      }
    }

    // 显示撤销模态框
    const showCancelModal = (order) => {
      cancelModal.value.order = order
      cancelModal.value.show = true
    }

// 撤销订单
    const cancelOrder = async () => {
      if (!cancelModal.value?.order?.orderId) {
        toast.error('订单信息缺失，无法撤销')
        return
      }

      const { orderId } = cancelModal.value.order

      try {
        const { code, data } = await userCancelOrder(orderId)

        if (code === 200) {
          // 更新本地状态
          const idx = orders.value?.findIndex(o => o.orderId === orderId)
          if (idx >= 0) {
            orders.value[idx] = {
              ...orders.value[idx],
              status: 'cancelled'
            }
          }

          toast.success(`订单 ${orderId} 已撤销`)
        } else {
          toast.error(data || '撤销订单失败')
        }
      } catch (err) {
        console.error('撤销订单失败:', err)
        toast.error('撤销订单时发生错误，请稍后重试')
      } finally {
        // 确保弹窗关闭
        cancelModal.value.show = false
        cancelModal.value.order = null
      }
    }


    // 格式化数字
    const formatNumber = (num) => {
      return new Intl.NumberFormat('zh-CN', {
        minimumFractionDigits: 0,
        maximumFractionDigits: 2
      }).format(num)
    }

    // 获取状态文本
    const getStatusText = (status) => {
      const statusMap = {
        'ing': '进行中',
        'done': '已完成',
        'cancel': '已撤销'
      }
      return statusMap[status.toLowerCase()] || status
    }

    // 获取状态样式类
    const getStatusClass = (status) => {
      const statusClassMap = {
        'ing': 'ing',
        'done': 'completed',
        'cancelled': 'cancelled'
      }
      return statusClassMap[status.toLowerCase()] || 'ing'
    }

    onMounted(() => {
      loadOrders()
    })

    return {
      loading,
      orders,
      cancelModal,
      showCancelModal,
      cancelOrder,
      formatNumber,
      getStatusText,
      getStatusClass
    }
  }
}
</script>

<style scoped>
.container {
  max-width: 1200px;
  margin: 0 auto;
  padding: 20px;
}

.header {
  background: white;
  padding: 24px;
  border-radius: 8px;
  box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
  margin-bottom: 24px;
}

.header h1 {
  font-size: 28px;
  font-weight: 600;
  color: #1a1a1a;
  margin-bottom: 8px;
}

.header p {
  color: #666;
  font-size: 16px;
}

.order-table {
  background: white;
  border-radius: 8px;
  box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
  overflow: hidden;
}

.table-header {
  background: #f8f9fa;
  padding: 16px 24px;
  border-bottom: 1px solid #e9ecef;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.table-title {
  font-size: 18px;
  font-weight: 600;
  color: #1a1a1a;
}

.order-count {
  color: #666;
  font-size: 14px;
}

table {
  width: 100%;
  border-collapse: collapse;
}

th, td {
  padding: 16px 24px;
  text-align: left;
  border-bottom: 1px solid #f0f0f0;
}

th {
  background: #fafafa;
  font-weight: 600;
  color: #333;
  font-size: 14px;
  text-transform: uppercase;
  letter-spacing: 0.5px;
}

td {
  font-size: 14px;
}

tr:hover {
  background-color: #f8f9fa;
}

.stock-symbol {
  font-weight: 600;
  color: #1a1a1a;
}

.buy-sell {
  padding: 4px 12px;
  border-radius: 20px;
  font-size: 12px;
  font-weight: 600;
  text-transform: uppercase;
}

.buy {
  width: 30px;
  background-color: #e8f5e8;
  color: #2e7d32;
}

.sell {
  width: 30px;
  background-color: #ffebee;
  color: #c62828;
}

.status {
  padding: 6px 12px;
  border-radius: 20px;
  font-size: 12px;
  font-weight: 500;
  text-align: center;
  min-width: 60px;
}

.status-ing {
  background-color: #fff3cd;
  color: #856404;
}

.status-completed {
  background-color: #d4edda;
  color: #155724;
}

.status-cancelled {
  background-color: #f8d7da;
  color: #721c24;
}

.cancel-btn {
  background: #fff;
  border: 1px solid #dc3545;
  color: #dc3545;
  padding: 6px 16px;
  border-radius: 4px;
  cursor: pointer;
  font-size: 12px;
  font-weight: 500;
  transition: all 0.2s ease;
}

.cancel-btn:hover {
  background: #dc3545;
  color: white;
  transform: translateY(-1px);
}

.cancel-btn:active {
  transform: translateY(0);
}

.amount {
  font-weight: 600;
}

.positive {
  color: #2e7d32;
}

.negative {
  color: #c62828;
}

.empty-state {
  padding: 48px 24px;
  text-align: center;
  color: #666;
}

.empty-state h3 {
  margin-bottom: 8px;
  color: #999;
}

.loading {
  padding: 48px 24px;
  text-align: center;
  color: #666;
}

.modal-overlay {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(0, 0, 0, 0.5);
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: 1000;
}

.modal {
  background: white;
  padding: 32px;
  border-radius: 8px;
  box-shadow: 0 10px 30px rgba(0, 0, 0, 0.2);
  max-width: 400px;
  width: 90%;
}

.modal h3 {
  margin-bottom: 16px;
  color: #1a1a1a;
}

.modal p {
  margin-bottom: 24px;
  color: #666;
  line-height: 1.5;
}

.modal-actions {
  display: flex;
  gap: 12px;
  justify-content: flex-end;
}

.btn {
  padding: 8px 20px;
  border: none;
  border-radius: 4px;
  cursor: pointer;
  font-size: 14px;
  font-weight: 500;
  transition: all 0.2s ease;
}

.btn-secondary {
  background: #f8f9fa;
  color: #666;
  border: 1px solid #dee2e6;
}

.btn-secondary:hover {
  background: #e9ecef;
}

.btn-danger {
  background: #dc3545;
  color: white;
}

.btn-danger:hover {
  background: #c82333;
  transform: translateY(-1px);
}

/* 响应式布局 */
.desktop-table {
  display: block;
}

.mobile-cards {
  display: none;
}

/* 移动端卡片样式 */
.order-card {
  border: 1px solid #f0f0f0;
  border-radius: 8px;
  margin-bottom: 16px;
  background: white;
  overflow: hidden;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 16px;
  background: #f8f9fa;
  border-bottom: 1px solid #f0f0f0;
}

.card-title {
  display: flex;
  align-items: center;
  gap: 12px;
}

.order-id {
  font-size: 14px;
  color: #666;
  font-weight: 500;
}

.card-content {
  padding: 16px;
}

.card-row {
  display: flex;
  justify-content: space-between;
  margin-bottom: 12px;
}

.card-row:last-child {
  margin-bottom: 0;
}

.card-item {
  flex: 1;
  display: flex;
  flex-direction: column;
  gap: 4px;
}

.card-item .label {
  font-size: 12px;
  color: #666;
  font-weight: 500;
}

.card-item .value {
  font-size: 14px;
  color: #1a1a1a;
  font-weight: 600;
}

.card-actions {
  padding: 16px;
  border-top: 1px solid #f0f0f0;
  background: #fafafa;
}

.cancel-btn-mobile {
  width: 100%;
  background: #fff;
  border: 1px solid #dc3545;
  color: #dc3545;
  padding: 10px 16px;
  border-radius: 4px;
  cursor: pointer;
  font-size: 14px;
  font-weight: 500;
  transition: all 0.2s ease;
}

.cancel-btn-mobile:hover {
  background: #dc3545;
  color: white;
}
.order-time{
  font-size: 12px;
  padding: 11px;
}

/* 平板和小屏幕适配 */
@media (max-width: 1024px) {
  th, td {
    padding: 12px 16px;
    font-size: 13px;
  }

  .cancel-btn {
    padding: 4px 12px;
    font-size: 11px;
  }
}

/* 移动端布局切换 */
@media (max-width: 840px) {
  .container {
    padding: 16px;
  }

  .header {
    padding: 20px;
  }

  .header h1 {
    font-size: 24px;
  }

  .desktop-table {
    display: none;
  }

  .mobile-cards {
    display: block;
  }

  .table-header {
    padding: 16px 20px;
  }

  .table-title {
    font-size: 16px;
  }

  .order-count {
    font-size: 13px;
  }
}

/* 超小屏幕优化 */
@media (max-width: 480px) {
  .container {
    padding: 12px;
  }

  .header {
    padding: 16px;
  }

  .header h1 {
    font-size: 20px;
  }

  .card-header {
    padding: 12px;
  }

  .card-content {
    padding: 12px;
  }

  .card-actions {
    padding: 12px;
  }

  .modal {
    margin: 16px;
    width: auto;
  }
}
</style>